//
//  SettingsViewController.m
//  wAudioShare
//
//  Created by Anson on 15-1-22.
//  Copyright (c) 2015年 赵帅. All rights reserved.
//

#import "SettingsViewController.h"

#import "CustomIOS7AlertView.h"
#import "Utitlity.h"
#import "MMProgressHUD.h"
#import "WISInterfaces.h"
#import "PersistableInfo.h"
#import "SettingsWifiHotSpotListView.h"
#import "SettingsNetWorkConfigView.h"

@interface SettingsViewController () <CustomIOS7AlertViewDelegate, SettingsWifiHotSpotListViewDelegate, SettingsNetWorkConfigViewDelegate, UITextFieldDelegate,UIAlertViewDelegate, MBProgressHUDDelegate>
{
    //chagne
    UIView *customAlertView;
    UITextField *oldPasswordTextField;
    UITextField *newPasswordTextField;
    UITextField *surePasswordTextField;
    //changeDeviceName
    UIView *changeNameAlertView;
    UITextField *changeNameTextField;
    
    //reset
    UIView *resetAlertView;
    UITextField *userNameTextField;
    UITextField *passWordTextField;
    
    NSString *ipUrl;
    BottomView *bottomView;
    
    NSString *oldDeviceName; //设备老名字
    
    SettingsNetWorkConfigView *_viewNetWorkConfig;//基本网络设置
    
    NSTimer *_timmerReqGetUpdateState;
}

@property (strong, nonatomic) NSArray *wifiHotSpotList;
@property (weak, nonatomic) IBOutlet UIView *checkUpdateView;
@property (weak, nonatomic) IBOutlet UITextField *tfCurrentVersion;
@property (weak, nonatomic) IBOutlet UITextField *tfLatestVersion;
@property (weak, nonatomic) IBOutlet UIButton *btnVersionUpdate;
@end

@implementation SettingsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    bottomView = [self addBottomView];
    self.checkUpdateView.hidden = YES;
    
    switch (self.viewType) {
        case SettingVCTypeDefault:
            [self layoutDefault];
            break;
        case SettingVCTypeNetWorkSetting:
            [self layoutNetWorkSetting];
            break;
        case SettingVCTypeDeviceProperties:
            [self layoutDeviceProperties];
            break;
        case SettingVCTypeDeviceFunction:
            [self layoutDeviceFunction];
            break;
        case SettingVCTypeCheckUpdate:{
            self.checkUpdateView.hidden = NO;
         
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self reqCheckLatestVersion];
            });
            break;
        }
        case SettingVCTypeNetWorkConfig:
        {
            //CGRect rect = CGRectMake(0, 0, , )
            [self layoutNetWorkConfig];
            break;
        }
        default:
            break;
    }
 
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//!**** 网络设定 ****//
- (void)layoutDefault {
    
    CGFloat y = 80;
    UIButton *btnNetWorkSetting = [self newButton:@"网络设定" sel:@selector(btnNetWorkSettingClicked:)];
    btnNetWorkSetting.center = CGPointMake(SCREEN_WIDTH/2, y);
    
    UIButton *btnDeviceFeature = [self newButton:@"设备属性" sel:@selector(btnDeviceFeatureClicked:)];
    btnDeviceFeature.center = CGPointMake(SCREEN_WIDTH/2, (y * 2));
    
    UIButton *btnDeviceFunction = [self newButton:@"设备功能" sel:@selector(btnDeviceFunctionClicked:)];
    btnDeviceFunction.center = CGPointMake(SCREEN_WIDTH/2, (y * 3));
    
    [self.view addSubview:btnNetWorkSetting];
    
    [self.view addSubview:btnDeviceFeature];
    
    [self.view addSubview:btnDeviceFunction];
    
}

//!**** 设备属性****//
- (void)layoutDeviceProperties {
    
    CGFloat y = 80;
    UIButton *btnNameModify = [self newButton:@"修改名称" sel:@selector(changNameTouch)];
    btnNameModify.center = CGPointMake(SCREEN_WIDTH/2, y);
    
    UIButton *btnPasswordModify = [self newButton:@"修改密码" sel:@selector(changePasswordTouch)];
    btnPasswordModify.center = CGPointMake(SCREEN_WIDTH/2, (y * 2));
    
    [self.view addSubview:btnNameModify];
    
    [self.view addSubview:btnPasswordModify];
    
}

//!**** 网络设定 ****//
- (void)layoutNetWorkSetting {
    
    CGFloat y = 80;
    UIButton *btnWifiNetWork = [self newButton:@"无线网络" sel:@selector(btnWifiNetWorkClicked:)];
    btnWifiNetWork.center = CGPointMake(SCREEN_WIDTH/2, y);
    
    UIButton *btnNetWorkConfig = [self newButton:@"网络设置" sel:@selector(btnNetWorkConfigClicked:)];
    btnNetWorkConfig.center = CGPointMake(SCREEN_WIDTH/2, (y * 2));
   
    [self.view addSubview:btnWifiNetWork];
    
    [self.view addSubview:btnNetWorkConfig];
    
}

//!***** 设备功能
- (void)layoutDeviceFunction {
    
    CGFloat y = 80;
    UIButton *btnRouteReset = [self newButton:@"路径重组" sel:nil];
    btnRouteReset.center = CGPointMake(SCREEN_WIDTH/2, y);
    
    UIButton *btnReset = [self newButton:@"恢复出厂" sel:nil];
    btnReset.center = CGPointMake(SCREEN_WIDTH/2, (y * 2));
    
    UIButton *btnRestart = [self newButton:@"重新启动" sel:nil];
    btnRestart.center = CGPointMake(SCREEN_WIDTH/2, (y * 3));
    
    UIButton *btnUpdateChck = [self newButton:@"检查更新" sel:@selector(btnUpdateCheckClicked:)];
    btnUpdateChck.center = CGPointMake(SCREEN_WIDTH/2, (y * 4));
    
    [self.view addSubview:btnRouteReset];
    [self.view addSubview:btnReset];
    [self.view addSubview:btnRestart];
    [self.view addSubview:btnUpdateChck];
}

- (UIButton *)newButton:(NSString *)title sel:(SEL)selector {
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [btn addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
    [btn setBackgroundColor:[UIColor getColor:@"4AA4DF"]];
    
    btn.frame = CGRectMake(0, 0, 150, 44);
    btn.layer.borderColor = [UIColor yellowColor].CGColor;
    btn.layer.borderWidth = 2.0f;
    btn.layer.cornerRadius = 20.0f;
    return btn;
}

- (void)layoutNetWorkConfig {
    
    self.title = @"网络设置";
    NSArray *dataList = @[ @{TEXT_LABEL_KEY:@"IP地址类型", TEXT_VALUE_KEY:@"静态IP"}, @{TEXT_LABEL_KEY:@"内网IP地址", TEXT_VALUE_KEY:@""} , @{TEXT_LABEL_KEY:@"子网掩码", TEXT_VALUE_KEY:@""}, @{TEXT_LABEL_KEY:@"默认网关", TEXT_VALUE_KEY:@""}, @{TEXT_LABEL_KEY:@"首选DNS服务器", TEXT_VALUE_KEY:@""}, @{TEXT_LABEL_KEY:@"备用DNS服务器", TEXT_VALUE_KEY:@""} ];
    
    SettingsNetWorkConfigView *viewConfig = [[SettingsNetWorkConfigView alloc] initWithFrame:self.view.frame dataSource:dataList];
    viewConfig.delegate = self;
    [self.view addSubview:viewConfig];
    _viewNetWorkConfig = viewConfig;
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self reqNetWorkConfigGetAddInfo];
    });
}

#pragma mark - UIButton
- (IBAction)btnNetWorkSettingClicked:(id)sender {
    
    SettingsViewController *vc = [[SettingsViewController alloc] init];
    vc.viewType = SettingVCTypeNetWorkSetting;
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (IBAction)btnDeviceFeatureClicked:(id)sender {
    
    SettingsViewController *vc = [[SettingsViewController alloc] init];
    vc.viewType = SettingVCTypeDeviceProperties;
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)btnDeviceFunctionClicked:(id)sender {
    
    SettingsViewController *vc = [[SettingsViewController alloc] init];
    vc.viewType = SettingVCTypeDeviceFunction;
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)btnWifiNetWorkClicked:(id)sender {

    [self reqDoWifiScan];
}

- (IBAction)btnNetWorkConfigClicked:(id)sender {
    SettingsViewController *vc = [[SettingsViewController alloc] init];
    vc.viewType = SettingVCTypeNetWorkConfig;
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (IBAction)btnUpdateCheckClicked:(id)sender {
    SettingsViewController *vc = [[SettingsViewController alloc] init];
    vc.viewType = SettingVCTypeCheckUpdate;
    [self.navigationController pushViewController:vc animated:YES];
}

//修改名字
- (void)changNameTouch
{
    CustomIOS7AlertView *alertView = [[CustomIOS7AlertView alloc] init];
    alertView.delegate = self;
    alertView.tag = 20000;
    [alertView setButtonTitles:[NSMutableArray arrayWithObjects:@"取消",@"确定", nil]];//添加按钮
    [alertView setContainerView:[self changeDeviceNameView:changeNameAlertView]];
    [alertView show];
}

//修改密码
- (void)changePasswordTouch
{
    CustomIOS7AlertView *alertView = [[CustomIOS7AlertView alloc] init];
    alertView.delegate = self;
    alertView.tag = 10000;
    [alertView setButtonTitles:[NSMutableArray arrayWithObjects:@"取消",@"确定", nil]];//添加按钮
    [alertView setContainerView:[self initializeAlertView:customAlertView]];
    [alertView show];
}

// 恢复出厂设置
- (void)resetChuChangeTouch
{
    CustomIOS7AlertView *alertView = [[CustomIOS7AlertView alloc] init];
    alertView.delegate = self;
    alertView.tag = 40000;
    [alertView setButtonTitles:[NSMutableArray arrayWithObjects:@"取消",@"确定", nil]];//添加按钮
    [alertView setContainerView:[self reSetView:resetAlertView]];
    [alertView show];
}

#pragma mark - Http Request
- (void)reqDoWifiScan {
    
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl)
    {
        [MMProgressHUD showWithStatus:@"WiFi扫描中...."];
        NSString *reqURL = [NSString stringWithFormat:@"http://%@/fcgi-bin/wifi.fcgi?action=do_scan",ipUrl];
        [Utitlity commonHTTPMethod:reqURL responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            NSLog(@"reOpenStr:%@",responseObject);
            if ([responseObject[@"state"] isEqualToString:@"Success"])
            {
                [MMProgressHUD showWithStatus:@"获取扫描结果...."];
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    
                    NSString *reqURL = [NSString stringWithFormat:@"http://%@/fcgi-bin/wifi.fcgi?action=do_getscan",ipUrl];
                    [Utitlity commonHTTPMethod:reqURL responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
                        if ([responseObject[@"state"] isEqualToString:@"Success"])
                        {
                            NSArray *apsList = responseObject[@"aps"];
                            if (apsList.count > 0) {
                                self.wifiHotSpotList = [NSArray arrayWithArray:apsList];
                                [self showWifiHotSpotListView];
                            }
                        }
                        [MMProgressHUD dismiss];
                        
                    }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                        NSLog(@"error:%@",error);
                        [MMProgressHUD dismissWithError:error.localizedDescription];
                    }];
                    
                });
         
            }
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error:%@",error);
            DLog(@"%@", operation.response.allHeaderFields);
            [MMProgressHUD dismissWithError:error.localizedDescription];
        }];
    }
}

- (void)showWifiHotSpotListView {
    
    CGRect rect = CGRectMake(0, 0, 200, 200);
    SettingsWifiHotSpotListView *view = [[SettingsWifiHotSpotListView alloc] initWithFrame:rect dataSource:self.wifiHotSpotList];
    view.delegate = self;
    view.tag = 1001;
    view.center = CGPointMake(SCREEN_WIDTH/2, rect.size.height);
    //[self.view addSubview:view];
    [view pageStart];
}

//!**** Wifi密码输入
- (void)reqWifiLoginWithPassword:(NSString *)passwordStr ssid:(NSString *)ssid
{
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl)
    {
        //ssid = @"IC-A"; passwordStr = @"Willis-ica2014";
        
        ssid = [Utitlity httpURLEncode:ssid];
        passwordStr = [Utitlity httpURLEncode:passwordStr];
        [MMProgressHUD showWithStatus:@"WiFi验证中...."];
        NSString *reOpenStr = [NSString stringWithFormat:@"http://%@/fcgi-bin/wifi.fcgi?action=do_conn&ssid=%@&passwd=%@",ipUrl, ssid, passwordStr];
        [Utitlity commonHTTPMethod:reOpenStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            NSLog(@"reOpenStr:%@",responseObject);
            if (![responseObject[@"state"] isEqualToString:@"Success"])
            {
                [MMProgressHUD dismissWithSuccess:@"WiFi验证失败！"];
                
            }else {
            
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    
                    NSString *req = [NSString stringWithFormat:@"http://%@/fcgi-bin/wifi.fcgi?action=do_getconn",ipUrl];
                    [Utitlity commonHTTPMethod:req responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
                        
                        NSLog(@"reOpenStr:%@",responseObject);
                        if ([responseObject[@"state"] isEqualToString:@"Success"]) {
                            [MMProgressHUD dismissWithSuccess:@"WiFi已连接成功！"];
                            [[self.view viewWithTag:1001] removeFromSuperview];
                        }else {
                            [MMProgressHUD dismissWithError:@"WiFi连接失败！"];
                        }
                    
                    }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                        NSLog(@"error:%@",error);
                        [MMProgressHUD dismissWithError:error.localizedDescription];
                    }];
                    
                });
            }
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error:%@",error);
            [MMProgressHUD dismissWithError:error.localizedDescription];
        }];
    }
}

//重启设备
- (void)reOpenTouch
{
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl)
    {
        NSString *reOpenStr = [NSString stringWithFormat:@"http://%@/cgi-bin/User.cgi?action=do_reboot&seconds=0",ipUrl];
        
        [Utitlity commonHTTPMethod:reOpenStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            NSLog(@"reOpenStr:%@",responseObject);
            if ([responseObject[@"state"] isEqualToString:@"Success"])
            {
                [MMProgressHUD showWithStatus:@"设备重新启动...."];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [MMProgressHUD dismissWithSuccess:@"重启成功"];
                });
                
                [self.navigationController popViewControllerAnimated:YES];
            }
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error:%@",error);
        }];
    }
}

//init changePasswordAlertView
- (UIView*)initializeAlertView:(UIView *)view
{
    view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 280, 133)];
    UILabel *changeLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 280, 30)];
    changeLabel.text = @"修改密码";
    changeLabel.textAlignment = UITextAlignmentCenter;
    UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(37, 30, 56, 22)];
    nameLabel.text = @"旧密码:";
    UILabel *userNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(37, 66, 56, 22)];
    userNameLabel.text = @"新密码:";
    UILabel *passwordLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 102, 73, 22)];
    passwordLabel.text = @"确认密码:";
    [view addSubview:nameLabel];
    [view addSubview:userNameLabel];
    [view addSubview:passwordLabel];
    [view addSubview:changeLabel];
    
    oldPasswordTextField = [[UITextField alloc] initWithFrame:CGRectMake(93, 30, 145, 22)];
    oldPasswordTextField.borderStyle = UITextBorderStyleBezel;
    oldPasswordTextField.delegate = self;
    newPasswordTextField = [[UITextField alloc] initWithFrame:CGRectMake(93, 66, 145, 22)];
    newPasswordTextField.borderStyle = UITextBorderStyleBezel;
    newPasswordTextField.delegate = self;
    surePasswordTextField = [[UITextField alloc] initWithFrame:CGRectMake(93, 102, 145, 22)];
    surePasswordTextField.borderStyle = UITextBorderStyleBezel;
    surePasswordTextField.delegate = self;
    [view addSubview:oldPasswordTextField];
    [view addSubview:newPasswordTextField];
    [view addSubview:surePasswordTextField];
    return view;
}

//changeDeviceName
-(UIView *)changeDeviceNameView:(UIView *)view
{
    view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 280, 133)];
    
    UILabel *connectlabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 20,280 , 22)];
    connectlabel.text = @"修改名字";
    connectlabel.font = [UIFont systemFontOfSize:18];
    connectlabel.textAlignment = UITextAlignmentCenter;
    UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(27, 56, 56, 22)];
    nameLabel.text = @"旧名称:";
    UILabel *userNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(27, 92, 83, 22)];
    userNameLabel.text = @"新名称:";
    [view addSubview:nameLabel];
    [view addSubview:connectlabel];
    [view addSubview:userNameLabel];
    
    UILabel *oldNameLbl = [[UILabel alloc] initWithFrame:CGRectMake(93, 56, 160, 22)];
    oldNameLbl.text = oldDeviceName;
    changeNameTextField = [[UITextField alloc] initWithFrame:CGRectMake(93, 92, 160, 22)];
    changeNameTextField.borderStyle = UITextBorderStyleBezel;
    changeNameTextField.delegate = self;
    [view addSubview:changeNameTextField];
    [view addSubview:oldNameLbl];
    
    return view;
}

-(UIView *)reSetView:(UIView *)view
{
    view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 280, 133)];
    
    UILabel *connectlabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 20,280 , 22)];
    connectlabel.text = @"恢复出厂设置";
    connectlabel.textAlignment = UITextAlignmentCenter;
    UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(37, 56, 56, 22)];
    nameLabel.text = @"用户名:";
    UILabel *userNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(54, 92, 73, 22)];
    userNameLabel.text = @"密码:";
    [view addSubview:nameLabel];
    [view addSubview:connectlabel];
    [view addSubview:userNameLabel];
    
    userNameTextField = [[UITextField alloc] initWithFrame:CGRectMake(93, 56, 145, 22)];
    userNameTextField.borderStyle = UITextBorderStyleBezel;
    userNameTextField.delegate = self;
    passWordTextField = [[UITextField alloc] initWithFrame:CGRectMake(93, 92, 145, 22)];
    passWordTextField.borderStyle = UITextBorderStyleBezel;
    passWordTextField.delegate = self;
    [view addSubview:userNameTextField];
    [view addSubview:passWordTextField];
    return view;
}

- (void)reqNetWorkConfigGetAddInfo {
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl)
    {
        [MMProgressHUD show];
        NSString *reqURL = [NSString stringWithFormat:@"http://%@/fcgi-bin/wifi.fcgi?action=do_getaddr",ipUrl];
        [Utitlity commonHTTPMethod:reqURL responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSLog(@"reOpenStr:%@",responseObject);
            if ([responseObject[@"state"] isEqualToString:@"Success"])
            {
                NSDictionary *lan = responseObject[@"lan"];
                //NSDictionary *wifi = responseObject[@"wifi"];
                //else if (wifi) dict = wifi;
            
                if (lan && _viewNetWorkConfig) {
                    BOOL dhcp = [responseObject[@"dhcp"] boolValue];
                    NSString *iface = lan[@"iface"];
                    NSString *addr = lan[@"addr"];
                    NSString *mask = lan[@"mask"];
                    NSString *gw = lan[@"gw"];
                    
                    NSArray *dataList = @[ @{TEXT_LABEL_KEY:@"IP地址类型", TEXT_VALUE_KEY:(dhcp == YES ? @"动态IP" : @"静态IP")}, @{TEXT_LABEL_KEY:@"内网IP地址", TEXT_VALUE_KEY:addr} , @{TEXT_LABEL_KEY:@"子网掩码", TEXT_VALUE_KEY:mask}, @{TEXT_LABEL_KEY:@"默认网关", TEXT_VALUE_KEY:gw}, @{TEXT_LABEL_KEY:@"首选DNS服务器", TEXT_VALUE_KEY:@""}, @{TEXT_LABEL_KEY:@"备用DNS服务器", TEXT_VALUE_KEY:@""} ];
                    [_viewNetWorkConfig setDataSource:dataList];
                }

            }
            
            [MMProgressHUD dismiss];
            
        }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error:%@ %@",error, operation.response.allHeaderFields);
            [MMProgressHUD dismissWithError:error.localizedDescription];
        }];
    }
}

- (void)reqSaveNetWorkConfig:(NSDictionary *)dict {
    
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl && dict)
    {
        [MMProgressHUD showWithStatus:@"检查更新中...."];
        NSString *reqURL = [NSString stringWithFormat:@"http://%@/fcgi-bin/wifi.fcgi?action=do_setaddr&iface=lan&dhcp=%@&addr=%@&mask=%@&gw=%@", ipUrl, dict[@"dhcp"], dict[@"addr"], dict[@"mask"], dict[@"gw"]];
        [Utitlity commonHTTPMethod:reqURL responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSLog(@"reOpenStr:%@",responseObject);
            if ([responseObject[@"state"] isEqualToString:@"Success"])
            {
                [MMProgressHUD dismissWithSuccess:@"保存成功"];
            }else
                [MMProgressHUD dismissWithError:@"保存失败"];
            
        }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error:%@",error);
            [MMProgressHUD dismissWithError:error.localizedDescription];
        }];
    }
}

- (void)reqCheckLatestVersion {
    
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl)
    {
        [self showMHUD:@"检查更新中...."];
        NSString *reqURL = [NSString stringWithFormat:@"http://%@/fcgi-bin/update.fcgi?action=do_check",ipUrl];
        [Utitlity commonHTTPMethod:reqURL responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSLog(@"reOpenStr:%@",responseObject);
            if ([responseObject[@"state"] isEqualToString:@"Success"])
            {
                self.tfCurrentVersion.text = responseObject[@"cur_ver"];
                self.tfLatestVersion.text = responseObject[@"new_ver"];
                self.btnVersionUpdate.hidden = ![responseObject[@"update"] boolValue];
            }
            
            [self hideMHUD];
            
        }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error:%@ , %@",error, operation.response.allHeaderFields);
            [MMProgressHUD dismissWithError:error.localizedDescription afterDelay:1.5];
        }];
    }
}

- (IBAction)reqLatestVersionUpdate:(id)sender {
    
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl)
    {
        BOOL isFirstReq = NO;
        if (sender) {
            [self showMHUD:@"检查更新中...."];
            isFirstReq = YES;
        }
        NSString *reqURL = [NSString stringWithFormat:@"http://%@/fcgi-bin/update.fcgi?action=do_update",ipUrl];
        [Utitlity commonHTTPMethod:reqURL responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSLog(@"reOpenStr:%@",responseObject);
            if ([responseObject[@"state"] isEqualToString:@"Success"])
            {
                if (isFirstReq) {
                    
                    [self showMHUD:responseObject[@"info"]];
                    [_timmerReqGetUpdateState invalidate];
                    _timmerReqGetUpdateState = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(reqLatestVersionUpdate:) userInfo:nil repeats:YES];
                    
                }
                else {
                    
                    NSInteger stageUpdate = [responseObject[@"update_stage"] integerValue];
                    [self showMHUD:responseObject[@"update_info"]];
                    if (stageUpdate == -1 || stageUpdate == 4) {
                        [_timmerReqGetUpdateState invalidate];
                    }
                }
            }
            
            
        }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error:%@",error);
            [self hideMHUD];
            [self toastMsg:error.localizedDescription];
        }];
    }
}

#pragma mark -
- (void)settingsNetWorkConfigView:(SettingsNetWorkConfigView *)view didSaveDataSrc:(NSDictionary *)data {
    
    [self reqSaveNetWorkConfig:data];
}

- (void)settingsWifiHotSpotListView:(SettingsWifiHotSpotListView *)view didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UIAlertView *promptInput = [[UIAlertView alloc] initWithTitle:@"请输入WIFI用户名和密码" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    promptInput.alertViewStyle = UIAlertViewStyleLoginAndPasswordInput;
    promptInput.delegate = self;
    [promptInput show];
    
}

#pragma mark - UIAlertView 
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        [self reqWifiLoginWithPassword:[alertView textFieldAtIndex:1].text ssid:[alertView textFieldAtIndex:0].text];
    }
}

#pragma mark - CustomIOS7Delegate
- (void)customIOS7dialogButtonTouchUpInside:(id)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //修改密码
    if([alertView tag] == 10000)
    {
        if (buttonIndex == 1)
        {
            [MMProgressHUD showWithTitle:@"修改密码中...."];
            if([newPasswordTextField.text isEqualToString:surePasswordTextField.text])
            {
                NSLog(@"oldPasswordTextField:%@ newPasswordTextField:%@,surePasswordTextField:%@ ",oldPasswordTextField.text,newPasswordTextField.text,surePasswordTextField.text);
                ipUrl = [Utitlity judgeipUrl];
                if (ipUrl)
                {
                    NSString *changPasswordStr = [NSString stringWithFormat:@"http://%@/cgi-bin/User.cgi?action=do_chpasswd&user=admin&passwd=%@&newpasswd=%@",ipUrl,oldPasswordTextField.text,surePasswordTextField.text];
                    
                    NSString * encodingString = [changPasswordStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                    NSLog(@"encodingString：%@",encodingString);
                    
                    [Utitlity commonHTTPMethod:encodingString responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
                        
                        NSLog(@"changePassword:%@",responseObject);
                        
                        if ([responseObject[@"state"] isEqualToString:@"Success"])
                        {
                            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                [MMProgressHUD dismissWithSuccess:@"修改密码成功"];
                            });
                        }
                    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                        NSLog(@"error:%@",error);
                    }];
                }
                
            }
            else
            {
                [MMProgressHUD dismissWithError:@"修改密码失败"];
            }
        }
    }
    else if([alertView tag] == 20000) //修改名称
    {
        if([changeNameTextField.text length] > 8)
        {
            changeNameTextField.text = [changeNameTextField.text substringToIndex:8];
        }
        
        NSLog(@"changeNameTextField:%@",changeNameTextField.text);
        if (buttonIndex == 1)
        {
            [MMProgressHUD showWithTitle:@"修改名称中...."];
            ipUrl = [Utitlity judgeipUrl];
            
            if ([changeNameTextField.text length] > 0 )
            {
                if (ipUrl)
                {
                    NSString *str = [NSString stringWithFormat:@"http://%@/cgi-bin/User.cgi?action=do_chdevname&oldname=%@&newname=%@",ipUrl,oldDeviceName,changeNameTextField.text];
                    
                    NSString * encodingString = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                    NSLog(@"encodingString：%@",encodingString);
                    
                    [Utitlity commonHTTPMethod:encodingString responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
                        
                        NSLog(@"changeName:%@",responseObject);
                        
                        if ([responseObject[@"state"] isEqualToString:@"Success"])
                        {
                            oldDeviceName = changeNameTextField.text;
                            [MMProgressHUD dismissWithSuccess:@"修改名称成功"];
                            
                            if (self.delegate) {
                                [self.delegate changeName:changeNameTextField.text];
                            }
                        }
                        
                    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                        NSLog(@"error:%@",error);
                    }];
                }
                else
                {
                    [MMProgressHUD dismissWithError:@"修改名称失败"];
                }
            }
            else
            {
                [MMProgressHUD dismissWithError:@"修改名称失败"];
            }
        }
    }
    else if ([alertView tag] == 40000)
    {
        if (buttonIndex == 1)
        {
            [MMProgressHUD showWithTitle:@"恢复出厂设置" status:@"恢复中....."];
            ipUrl = [Utitlity judgeipUrl];
            
            if (ipUrl)
            {
                NSString *resetStr = [NSString stringWithFormat:@"http://%@/cgi-bin/User.cgi?action=do_factory&user=%@&passwd=%@",ipUrl,userNameTextField.text,passWordTextField.text];
                NSString * encodingString = [resetStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                
                [Utitlity commonHTTPMethod:encodingString responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
                    NSLog(@"resetStr:%@",responseObject);
                    
                    if ([responseObject[@"state"] isEqualToString:@"Success"])
                    {
                        //子线程删除缓存
                        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                            NSString *uuidS = [[GlobalService sharedInstance].curOperationDeviceUUID stringByReplacingOccurrencesOfString:@":" withString:@""];
                            NSArray *array = [PersistableInfo findByCriteria:@"'%@%'",uuidS];
                            NSLog(@"array:%@",array);
                            
                            for (PersistableInfo *deleInfo in array)
                            {
                                NSString *uuid = deleInfo.uuid;
                                [PersistableInfo deleteByCriteria:@"where uuid = '%@'",uuid];
                            }
                            
                        });
                        
                        //同时断连设备
                        [MMProgressHUD dismissWithSuccess:@"恢复成功"];
                        
                        wis_user_dev device;
                        [self.value getValue:&device];
                        
                        if (self.delegate) {
                            [self.delegate unConnectDevice:device.uuid];
                        }
                        
                        [self.navigationController popViewControllerAnimated:YES];
                    }
                    else
                    {
                        [MMProgressHUD dismissWithError:@"输入账号密码错误"];
                    }
                    
                } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                    NSLog(@"error:%@",error);
                }];
            }
        }
        
    }
    
    [alertView close];
    
}
@end
